#============================================================
#	Move Controller
#============================================================
# @datetime: 2022-5-18 20:44:32
#============================================================
class_name MoveController
extends Parasitic


## 移动状态发生改变
signal move_state_changed(state)
## 方向发生改变
signal direction_changed(direction)


export var host : NodePath
export var move_speed : float = 0
export (float, 0, 1) var friction : float = 1.0


var move_enabled : bool = true
var motion_velocity : Vector2

# 上次移动的向量
var __last_velocity__ : Vector2 = Vector2(0,0)
# 实时移动速度
var __move_speed__ : float = 0.0
# 是否正在移动
var __moving__ : bool = false setget _set_move
# 移动方向
var __direction__ : Vector2 = Vector2(0,0)


#============================================================
#   Set/Get
#============================================================
#(override)
func get_host():
	return .get_host() as KinematicBody2D

func set_host(value: KinematicBody2D):
	__host__ = value

func is_moving() -> bool:
	return __moving__

func get_last_velocity() -> Vector2:
	return __last_velocity__

func _set_move(value: bool):
	if __moving__ != value:
		__moving__ = value
		emit_signal("move_state_changed", __moving__)


#============================================================
#   内置
#============================================================
func _ready():
	if __host__ == null and host:
		set_host(get_node_or_null(host))
	if __host__ == null:
		__host__ = get_parent()
		assert(get_parent() is KinematicBody2D, "父节点必须是 KinematicBody2D 类型")


func _physics_process(delta):
	_move(delta)


#============================================================
#   自定义
#============================================================
##  移动
func _move(delta: float) -> void:
	__last_velocity__ = motion_velocity
	get_host().move_and_slide(motion_velocity)
	motion_velocity = Vector2(0, 0)


##  更新数据
## @dir  
func _update_state(dir: Vector2):
	if dir != Vector2(0,0):
		update_direction(dir)
		__move_speed__ = move_speed
		__moving__ = true
	else:
		__move_speed__ = lerp(__move_speed__, 0.0, friction)
		__moving__ = false


##  更新方向
## @dir  
func update_direction(dir: Vector2):
	if __direction__ != dir:
		__direction__ = dir 
		emit_signal("direction_changed", __direction__)


##  根据方向移动 
## @direction  
func move_direction(direction: Vector2):
	if move_enabled:
		move_vector(direction * __move_speed__)


##  根据向量移动 
## @velocity  
func move_vector(velocity: Vector2):
	if move_enabled:
		_update_state(velocity.normalized())
		motion_velocity = velocity

